package com.mframe.web.controller.activiti;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.activiti.engine.task.TaskQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.mframe.activiti.domain.Audit;
import com.mframe.activiti.domain.AuditDetail;
import com.mframe.activiti.mapper.AuditMapper;
import com.mframe.activiti.service.IAuditDetailService;
import com.mframe.activiti.service.IAuditService;
import com.mframe.activiti.service.Impl.AuditDetailServiceImpl;
import com.mframe.activiti.task.MulitiInstanceCompleteTask;
import com.mframe.common.base.AjaxResult;
import com.mframe.framework.web.page.TableDataInfo;
import com.mframe.system.domain.SysUserRole;
import com.mframe.system.service.ISysUserService;
import com.mframe.web.core.base.BaseController;

/**
 * 审核 信息操作处理
 * 
 * @author mframe
 * @date 2018-11-13
 */
@Controller
@RequestMapping("/activiti/audit")
public class AuditController extends BaseController {
	private String prefix = "activiti/audit";

	@Autowired
	private IAuditDetailService auditDetailService;

	@Autowired
	private IAuditService auditService;

	@Autowired
	private RuntimeService runtimeService;

	@Autowired
	private ISysUserService userService;

	@Autowired
	private TaskService taskService;

	@GetMapping()
	public String audit() {
		return prefix + "/audit";
	}

	// 进入审核页面
	@GetMapping("/doAudit")
	public String doAudit() {
		return "activiti/doAudit/doAudit";
	}

	/**
	 * 查询申请列表
	 */
	@PostMapping("/list")
	@ResponseBody
	public TableDataInfo list(Audit audit) {
		startPage();
		List<Audit> list = auditService.selectAuditList(audit);
		return getDataTable(list);
	}

	/**
	 * 新增审核
	 */
	@GetMapping("/add")
	public String add() {
		return prefix + "/add";
	}

	/**
	 * 新增保存审核
	 */
	@PostMapping("/add")
	@ResponseBody
	public AjaxResult addSave(Audit audit) {
		audit.setUserId(getUserId().intValue());
		audit.setCreateTime(new Date());
		Map<String, Object> variables = new HashMap<String, Object>();
		List<String> users = userService.findUserByRole("1,2,3");
		if (users.size() < 2) {
			return AjaxResult.error("当前系统审核人数不足，无法申请");
		}
		if (users.size() == 2) {
			users.add("-1");
		}
		variables.put("leaderList", users);
		ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(audit.getType(), variables);
		audit.setPid(processInstance.getId());
		Task task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
		taskService.complete(task.getId());
		return toAjax(auditService.insertAudit(audit));
	}

	/**
	 * 修改审核
	 */
	@GetMapping("/edit/{id}")
	public String edit(@PathVariable("id") Integer id, ModelMap mmap) {
		Audit audit = auditService.selectAuditById(id);
		mmap.put("audit", audit);
		return prefix + "/edit";
	}

	/**
	 * 修改保存审核
	 */
	@PostMapping("/edit")
	@ResponseBody
	public AjaxResult editSave(Audit audit) {
		return toAjax(auditService.updateAudit(audit));
	}

	/**
	 * 删除审核
	 */
	@PostMapping("/remove")
	@ResponseBody
	public AjaxResult remove(String ids) {
		return toAjax(auditService.deleteAuditByIds(ids));
	}

	/**
	 * 查询申请列表
	 */
	@PostMapping("/doAuditlist")
	@ResponseBody
	public TableDataInfo doAuditlist(Audit audit) {
		String userId = getUserId().toString();
		TaskQuery taskQuery = taskService.createTaskQuery().taskAssignee(userId).orderByTaskCreateTime().desc();
		List<Task> tasksList = taskQuery.list();
		List<String> pids = new ArrayList<>();
		for (Task t : tasksList) {
			pids.add(t.getProcessInstanceId());
		}
		if (pids.size() == 0) {
			pids.add("-1");
		}
		startPage();
		List<Audit> list = auditService.selectAuditListByPids(pids);
		for (Audit li : list) {
			for (Task tk : tasksList) {
				if (Objects.equals(li.getPid(), tk.getProcessInstanceId())) {
					li.setTaskId(tk.getId());
					break;
				}
			}
		}
		return getDataTable(list);
	}

	@PostMapping("/agree")
	@ResponseBody
	public AjaxResult agree(Integer id, String taskId) {
		Map<String, Object> variables = new HashMap<String, Object>();
		variables.put("mulitiInstance", new MulitiInstanceCompleteTask());
		SysUserRole ur = userService.findUserWithRole(getUser().getUserId());
		Audit audit = auditService.selectAuditById(id);
		AuditDetail auditDetail = new AuditDetail();
		auditDetail.setAuditId(audit.getId());
		auditDetail.setStatus(1);
		auditDetail.setUserId(getUser().getUserId().toString());
		auditDetail.setUserRole(ur.getRoleId().toString());
		auditDetail.setCreateTime(new Date());
		int i = auditDetailService.insertAuditDetail(auditDetail);
		taskService.complete(taskId, variables);
		return toAjax(i);
	}
	
	@PostMapping("/reject")
	@ResponseBody
	public AjaxResult reject(Integer id, String taskId) {
		Map<String, Object> variables = new HashMap<String, Object>();
		variables.put("mulitiInstance", new MulitiInstanceCompleteTask());
		SysUserRole ur = userService.findUserWithRole(getUser().getUserId());
		Audit audit = auditService.selectAuditById(id);
		AuditDetail auditDetail = new AuditDetail();
		auditDetail.setAuditId(audit.getId());
		auditDetail.setStatus(0);
		auditDetail.setUserId(getUser().getUserId().toString());
		auditDetail.setUserRole(ur.getRoleId().toString());
		auditDetail.setCreateTime(new Date());
		int i = auditDetailService.insertAuditDetail(auditDetail);
		taskService.complete(taskId, variables);
		return toAjax(i);
	}

}
